import type {ComponentConfig} from "@/lib/types"

export function generateDataComponent(config: ComponentConfig): string {
    const {name, description, features} = config

    // 检查是否启用了特定功能
    const hasPagination = features.some((f) => f.id === "pagination" && f.enabled)
    const hasSearch = features.some((f) => f.id === "search" && f.enabled)
    const hasLifecycle = features.some((f) => f.id === "lifecycle" && f.enabled)

    return `<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';

/**
 * ${description || `${name} 数据展示组件`}
 */
interface DataItem {
  id: number;
  name: string;
  email: string;
  role: string;
  status: 'active' | 'inactive';
}

interface Props {
  title?: string;
  loading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: '用户列表',
  loading: false
});

const items = ref<DataItem[]>([]);
${hasSearch ? "const searchQuery = ref('');" : ""}
${
        hasPagination
            ? `const currentPage = ref(1);
const itemsPerPage = 5;`
            : ""
    }

// 模拟获取数据
const fetchData = () => {
  // 在实际应用中，这里会是一个API调用
  const mockData: DataItem[] = [
    { id: 1, name: '张三', email: 'zhangsan@example.com', role: '管理员', status: 'active' },
    { id: 2, name: '李四', email: 'lisi@example.com', role: '用户', status: 'active' },
    { id: 3, name: '王五', email: 'wangwu@example.com', role: '编辑', status: 'inactive' },
    { id: 4, name: '赵六', email: 'zhaoliu@example.com', role: '用户', status: 'active' },
    { id: 5, name: '钱七', email: 'qianqi@example.com', role: '用户', status: 'inactive' },
    { id: 6, name: '孙八', email: 'sunba@example.com', role: '编辑', status: 'active' },
    { id: 7, name: '周九', email: 'zhoujiu@example.com', role: '用户', status: 'active' },
  ];
  
  items.value = mockData;
};

${
        hasSearch
            ? `// 过滤数据
const filteredItems = computed(() => {
  if (!searchQuery.value) return items.value;
  
  const query = searchQuery.value.toLowerCase();
  return items.value.filter(item => 
    item.name.toLowerCase().includes(query) || 
    item.email.toLowerCase().includes(query) ||
    item.role.toLowerCase().includes(query)
  );
});`
            : "const filteredItems = computed(() => items.value);"
    }

${
        hasPagination
            ? `// 分页数据
const paginatedItems = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage;
  return filteredItems.value.slice(startIndex, startIndex + itemsPerPage);
});

// 总页数
const totalPages = computed(() => 
  Math.ceil(filteredItems.value.length / itemsPerPage)
);

// 页码数组
const pageNumbers = computed(() => {
  const pages = [];
  for (let i = 1; i <= totalPages.value; i++) {
    pages.push(i);
  }
  return pages;
});`
            : "const paginatedItems = computed(() => filteredItems.value);"
    }

${
        hasLifecycle
            ? `// 组件挂载时获取数据
onMounted(fetchData);`
            : "// 初始化数据\nfetchData();"
    }
</script>

<template>
  <div class="bg-white shadow-md rounded-lg overflow-hidden">
    <div class="p-4 border-b">
      <h2 class="text-lg font-medium text-gray-900">{{ title }}</h2>
      ${
        hasSearch
            ? `<div class="mt-2">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索..."
          class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
        />
      </div>`
            : ""
    }
    </div>
    
    <div class="overflow-x-auto">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              姓名
            </th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              邮箱
            </th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              角色
            </th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
              状态
            </th>
            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
              操作
            </th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <template v-if="loading">
            <tr>
              <td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500">
                加载中...
              </td>
            </tr>
          </template>
          <template v-else-if="paginatedItems.length === 0">
            <tr>
              <td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500">
                没有找到匹配的数据
              </td>
            </tr>
          </template>
          <template v-else>
            <tr v-for="item in paginatedItems" :key="item.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                {{ item.name }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ item.email }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ item.role }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span 
                  class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                  :class="{
                    'bg-green-100 text-green-800': item.status === 'active',
                    'bg-red-100 text-red-800': item.status === 'inactive'
                  }"
                >
                  {{ item.status === 'active' ? '活跃' : '停用' }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <a href="#" class="text-primary hover:text-primary/80 mr-3">编辑</a>
                <a href="#" class="text-red-600 hover:text-red-900">删除</a>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
    
    ${
        hasPagination
            ? `<!-- 分页 -->
    <div class="px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
      <div class="flex-1 flex justify-between sm:hidden">
        <button 
          @click="currentPage = Math.max(1, currentPage - 1)"
          :disabled="currentPage === 1"
          class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }"
        >
          上一页
        </button>
        <button 
          @click="currentPage = Math.min(totalPages, currentPage + 1)"
          :disabled="currentPage === totalPages"
          class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }"
        >
          下一页
        </button>
      </div>
      <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
        <div>
          <p class="text-sm text-gray-700">
            显示第 <span class="font-medium">{{ (currentPage - 1) * itemsPerPage + 1 }}</span> 到 
            <span class="font-medium">{{ Math.min(currentPage * itemsPerPage, filteredItems.length) }}</span> 条，
            共 <span class="font-medium">{{ filteredItems.length }}</span> 条结果
          </p>
        </div>
        <div>
          <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
            <button 
              @click="currentPage = Math.max(1, currentPage - 1)"
              :disabled="currentPage === 1"
              class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
              :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }"
            >
              <span class="sr-only">上一页</span>
              <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                <path fillRule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clipRule="evenodd" />
              </svg>
            </button>
            <button 
              v-for="page in pageNumbers" 
              :key="page"
              @click="currentPage = page"
              class="relative inline-flex items-center px-4 py-2 border text-sm font-medium"
              :class="currentPage === page ? 'z-10 bg-primary/10 border-primary text-primary' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'"
            >
              {{ page }}
            </button>
            <button 
              @click="currentPage = Math.min(totalPages, currentPage + 1)"
              :disabled="currentPage === totalPages"
              class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
              :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }"
            >
              <span class="sr-only">下一页</span>
              <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                <path fillRule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clipRule="evenodd" />
              </svg>
            </button>
          </nav>
        </div>
      </div>
    </div>`
            : ""
    }
  </div>
</template>`
}
